package com.carworld.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.carworld.model.base.BaseUserReserve;
import com.carworld.utils.DicUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class UserReserve extends BaseUserReserve<UserReserve> {
	public static final UserReserve dao = new UserReserve().dao();

	/**
	 * 设置缓存，查询客户信息 暂未使用
	 *
	 * @param userId
	 * @param reserveId
	 * @param reserveStatus
	 *            0为查询未处理预约，1为查询已处理预约
	 * @return 利用分页，显示1页3条数据
	 */
	public Page<Record> findReserveInCache(String userId, String reserveId, String reserveStatus) {
		List<String> whereParams = new ArrayList<String>();
		String sqlString = " SELECT ur.* ";
		StringBuffer sBuffer = new StringBuffer("FROM user_reserve ur ");
		sBuffer.append(" WHERE 1=1 ");
		// 动态传参
		this.addEqualCondition(sBuffer, whereParams, "ur.user_id", userId);
		this.addEqualCondition(sBuffer, whereParams, "ur.reserve_id", reserveId);
		this.addEqualCondition(sBuffer, whereParams, "ur.reserve_status", reserveStatus);
		String key = userId + reserveStatus + reserveId;
		return Db.paginateByCache(DicUtil.CACHE_USER_RESERVE, key, 1, 3, sqlString, sBuffer.toString(),
				whereParams.toArray());
	}
	//查询某人未处理预约条数
	public int findReserveIn(String userId,String reserveStatus) {
		String sqlString = "SELECT  count(*) FROM user_reserve ur WHERE   ur.user_id=? and ur.reserve_status=?";
		return Db.queryInt(sqlString, userId, reserveStatus);
	}

	/**
	 * 根据用户id保存提交的预约订单
	 * 
	 * @param userReserve
	 * @param userId
	 * @return
	 */
	public String saveUserReserve(UserReserve userReserve, String userId) {
		String result = "未知错误";
		// 查询用户是否有未完成的预约订单
		int count = this.findReserveIn(userId, "0");
//		System.out.println("page.getTotalRow():::"+page.getTotalRow() );
		if (count>3) {
			result = "店内正忙,预约请直接拨打(02)89580828 ! \n The shop is busy.please call (02)89580828 ";
		} else {
			userReserve.setReserveId(getIds());
			userReserve.setUserId(userId);
			userReserve.setUserName(userReserve.getUserName());
			userReserve.setUserMobile(userReserve.getUserMobile());
			userReserve.setShopId(userReserve.getShopId());
			userReserve.setShopName(userReserve.getShopName());
			userReserve.setReserveContent(userReserve.getReserveContent());
			userReserve.setReserveTime(userReserve.getReserveTime());
			userReserve.setReserveRemark(userReserve.getReserveRemark());
			userReserve.setReserveStatus("0");
			Date date = new Date();
			userReserve.setCreateTime(date);
			userReserve.setUpdateTime(date);
			userReserve.save();
			// 预约成功之后发送通知给客户和对应门店店长
			this.reserveNotification(userReserve);
			result = "预约成功!\n用餐高峰期本店会给您最多延长预约时间10分钟哦,请谅解. ";
		}
		return result;
	}

	public JSONObject reserveNotification(UserReserve userReserve) {

		SysUser user = SysUser.dao.findByIdInCache(userReserve.getUserId());
		SysOffice officeInfo = SysOffice.dao.findShopInCache(userReserve.getShopId());
//		SysUser userOfOfficer = SysUser.dao.findByIdInCache(officeInfo.getPrimaryPerson());//根据店查店长对象sql错误

		// 预约成功后通知客户
//		if (StrKit.notBlank(user.getUserOpenid())) {
//			ApiResult apiResultOfCustomer = TemplateMsgApi.send(TemplateData.New().setTouser(user.getUserOpenid())// 消息接收者
//					.setTemplate_id("PDFNZH0m44FT0sScKkF3pXzX4zirREmYkWkToFJ97Nw") // 预约成功通知的模板id
//					// 模板参数
//					.add("first", "您已经成功预约\n")
//					.add("keyword1", userReserve.getReserveContent(), "#173177")
//					.add("keyword2", userReserve.getReserveTime().toString(), "#173177")
//					.add("keyword3", userReserve.getUserName(), "#173177")
//					.add("keyword4", officeInfo.getPhone(), "#173177")
//					.add("keyword5", officeInfo.getName() + "\n", "#173177")
//					.add("remark", "亲爱的小主儿~ ，我们在【" + officeInfo.getAddress() + "】等您呦~", "#173177").build());
//			System.out.println("通知客户模板消息结果：" + apiResultOfCustomer.getJson());
//		}

		// 预约成功后通知店长
		if (StrKit.notBlank("ocgWcwiaISXLqsy1E5a-NulA2RHM")) {
			ApiResult apiResultOfOfficer = TemplateMsgApi.send(TemplateData.New()
					.setTouser("ocgWcws9Z8X-BV1bAOTTj0ExM_oo")// 消息接收者
					.setTemplate_id("M5IB6rb8fbBPLRtMbn_tDGim9JjHJ7YYq8xERjX_EJE") // 客户预约通知的模板id
					// 模板参数
					.add("first", userReserve.getUserName()+"发起新的预约，请及时确认\n")
					.add("keyword1","茉德火锅店" , "#173177")//userReserve.getUserName()
					.add("keyword2", userReserve.getReserveSize(), "#173177")
					.add("keyword3", userReserve.getReserveTime().toString(), "#173177")
					.add("keyword4", userReserve.getUserMobile() + "\n", "#173177")
					.add("keyword5", userReserve.getReserveRemark() + "\n", "#173177")
					.add("remark", "请在pc端处理该预约,查看预约内容", "#173177").build());
			System.out.println("通知店长模板消息结果：" + apiResultOfOfficer.getJson());
		}

		CacheKit.remove(DicUtil.CACHE_USER_RESERVE, userReserve.getUserId());
		return sendSuccessJson("预约成功!");
	}

}
